package com.suredy.app.plan.ctrl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.suredy.app.area.model.Area;
import com.suredy.app.area.service.AreaSrv;
import com.suredy.app.detection.entity.ColorimetryEntity;
import com.suredy.app.detection.entity.ColorimetryItemEntity;
import com.suredy.app.detection.entity.Detection;
import com.suredy.app.detection.entity.NakedMatterEntity;
import com.suredy.app.detection.entity.NakedMatterItemEntity;
import com.suredy.app.detection.entity.PHValueEntity;
import com.suredy.app.detection.entity.PHValueItemEntity;
import com.suredy.app.detection.entity.SmellandTasteEntity;
import com.suredy.app.detection.entity.SmellandTasteItemEntity;
import com.suredy.app.detection.entity.TurbidityEntity;
import com.suredy.app.detection.entity.TurbidityItemEntity;
import com.suredy.app.plan.model.PlanInfo;
import com.suredy.app.plan.model.PlanPlace;
import com.suredy.app.plan.model.PlanTestItem;
import com.suredy.app.plan.service.PlanItemSrv;
import com.suredy.app.plan.service.PlanSrv;
import com.suredy.app.plan.service.PlanTestItemSrv;
import com.suredy.app.plan.service.TestTypeSrv;
import com.suredy.app.testItem.model.TestItem;
import com.suredy.app.testItem.service.TestItemSrv;
import com.suredy.app.testType.model.TestType;
import com.suredy.core.ctrl.BaseFlowCtrl;
import com.suredy.core.mvc.model.MessageModel;
import com.suredy.core.mvc.model.Tree;
import com.suredy.security.entity.User2RoleEntity;
import com.suredy.security.model.Role;
import com.suredy.security.model.User;
import com.suredy.security.service.RoleSrv;
import com.suredy.security.service.User2RoleSrv;

@Controller
@RequestMapping({"/plan"})
public class PlanCtrl extends BaseFlowCtrl {

	@Value("${SYS.MAIN_FLOW}")
	private String mainFlow;

	@Value("${SYS.TEST_FLOW}")
	private String testFlow;

	@Autowired
	private PlanSrv plansrv;

	@Autowired
	private PlanItemSrv planItemsrv;

	@Autowired
	private TestItemSrv testItemsrv;

	@Autowired
	private AreaSrv tpsrv;

	@Autowired
	private PlanTestItemSrv ptisrv;

	@Autowired
	private TestTypeSrv ttsrv;

	@Autowired
	private RoleSrv rsrv;

	@Autowired
	private User2RoleSrv ursrv;

	@RequestMapping({"/saveForm"})
	@ResponseBody
	public boolean save(@RequestBody PlanInfo plan) {
		PlanInfo _plan = plansrv.get(plan.getId());
		_plan.setPlanDate(plan.getPlanDate());
		plansrv.update(_plan);
		SimpleDateFormat d = new SimpleDateFormat("yyyyMMdd");
		this.updateTodo(_plan, "采样检测计划-["+d.format(plan.getPlanDate())+"]", this.createTodoUri("/plan/planform/{id}", plan.getId()));
		return true;
	}

	@RequestMapping({"/planform/{id}"})
	public ModelAndView form(@PathVariable String id) {
		ModelAndView view = new ModelAndView("/app/plan/planform");
		PlanInfo plan = plansrv.get(id);
		view.addObject("plan", plan);
		return view;
	}

	@RequestMapping({"/new"})
	@ResponseBody
	public ModelAndView newPlan() {
		PlanInfo plan = new PlanInfo();
		plan.setPlanDate(new Date());
		this.createFlow(plan, "plan", mainFlow, "/plan/planform/{id}");
		ModelAndView view = new ModelAndView(new RedirectView("planform/" + plan.getId()));
		return view;
	}

	@RequestMapping({"/selgrabber"})
	@ResponseBody
	public ModelAndView selGrabber() {
		Role r = rsrv.getByName("采样员");
		List<User2RoleEntity> ue = ursrv.getByRole(r.getId());
		List<User> userList = new ArrayList<User>();
		for (User2RoleEntity u : ue) {
			userList.add(u.getUser().toVO());
		}
		ModelAndView view = new ModelAndView("/app/plan/sel-grabber");
		view.addObject("userList", userList);
		return view;
	}

	@RequestMapping({"/setinspector"})
	@ResponseBody
	public ModelAndView setInspector() {
		Role r = rsrv.getByName("检测员");
		List<User> userList = new ArrayList<User>();
		if (r != null) {
			List<User2RoleEntity> ue = ursrv.getByRole(r.getId());
			for (User2RoleEntity u : ue) {
				userList.add(u.getUser().toVO());
			}
		}
		ModelAndView view = new ModelAndView("/app/plan/sel-grabber");
		view.addObject("userList", userList);

		return view;
	}

	@RequestMapping({"/selplace"})
	public ModelAndView selPlace() {
		List<Tree> l = new ArrayList<Tree>();
		List<Area> placeList = tpsrv.getAll();
		for (Area p : placeList) {
			Tree t = new Tree();
			t.setText(p.getName());
			t.setData(p.getCode());
			l.add(t);
		}
		ModelAndView view = new ModelAndView("/app/plan/sel-place");
		String jsonStr = "";
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			jsonStr = objectMapper.writeValueAsString(l);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		view.addObject("treeData", jsonStr);
		view.addObject("selectedId", "");
		return view;
	}

	@RequestMapping({"/saveItem"})
	@ResponseBody
	public List<PlanPlace> savaItem(@RequestBody List<PlanPlace> items) {
		for (PlanPlace item : items) {
			if (StringUtils.isEmpty(item.getId())) {
				PlanInfo plan = new PlanInfo();
				plan.setId(item.getPlanInfoId());
				item.setPlanInfo(plan);
				planItemsrv.save(item);
			} else {
				PlanPlace _item = planItemsrv.get(item.getId());
				if (!StringUtils.isEmpty(item.getGrabberId())) {
					_item.setGrabberId(item.getGrabberId());
					_item.setGrabberName(item.getGrabberName());
				}
				if (!StringUtils.isEmpty(item.getTestTypeId())) {
					_item.setTestTypeId(item.getTestTypeId());
					_item.setTestTypeName(item.getTestTypeName());
				}
				planItemsrv.update(_item);
			}
		}
		return items;
	}

	@RequestMapping({"/delitem"})
	@ResponseBody
	public String delItem(@RequestBody List<PlanPlace> items) {
		for (PlanPlace item : items)
			planItemsrv.delete(item);
		return "success";
	}

	@RequestMapping({"/seltesttype"})
	public ModelAndView selTestType() {
		List<TestType> typeList = ttsrv.getAll();
		ModelAndView view = new ModelAndView("/app/plan/sel-testtype");
		view.addObject("typeList", typeList);
		return view;
	}

	@RequestMapping({"/finishGrab"})
	@ResponseBody
	public String finishGrab(String planId) {
		PlanInfo plan = plansrv.get(planId);
		Set<PlanTestItem> itemSet = plan.getTestItems();
		List<TestItem> items = testItemsrv.getAll();
		for (TestItem t : items) {
			PlanTestItem pti = new PlanTestItem();
			pti.setPlanInfo(plan);
			pti.setTestCode(t.getCode());
			pti.setTestName(t.getName());
			itemSet.add(pti);
		}
		for (PlanPlace tp : plan.getPlanItems()) {
			tp.setStatus(1);
		}
		plan.setStatus(2);
		plansrv.update(plan);
		return "success";
	}

	@RequestMapping({"/updateinspector"})
	@ResponseBody
	public String updateTestItem(@RequestBody List<PlanTestItem> items) {
		for (PlanTestItem item : items) {
			PlanTestItem _item = ptisrv.get(item.getId());
			_item.setInspectorId(item.getInspectorId());
			_item.setInspectorName(item.getInspectorName());
			ptisrv.update(_item);
		}
		return "success";
	}

	// 完成采样点设置，并生成样品编码
	@RequestMapping({"/finishplace"})
	@ResponseBody
	public String finishPlace(String planId) {
		PlanInfo plan = plansrv.get(planId);
		SimpleDateFormat d = new SimpleDateFormat("yyyyMMdd");
		String code = d.format(plan.getPlanDate());
		int i = 1;
		for (PlanPlace p : plan.getPlanItems()) {
			p.setCode(code + p.getTestTypeId() + "_" + i);
			i++;
		}
		plan.setStatus(1);
		plansrv.update(plan);
		return "success";
	}

	@RequestMapping({"/createTest"})
	@ResponseBody
	public String createTest(String planId) {
		PlanInfo plan = plansrv.get(planId);
		String uri;
		String title;
		Detection job;
		SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd");
		String code = d.format(plan.getPlanDate());
		if (plan != null) {
			for (PlanTestItem t : plan.getTestItems()) {
				uri = "";
				title = "";
				job=null;
				switch (t.getTestCode()) {
					case "SD":
						title="色度检测任务["+code+"]";
						uri="/app/detection/colorimetry-detail/{id}";
						job = new ColorimetryEntity();
						job.setSampleDate(plan.getPlanDate());
						job.setDetector(t.getInspectorId()); 
						job.setDetectorName(t.getInspectorName()); 
						job.setPlanId(planId);
						job.setJobId(t.getId());
						List<ColorimetryItemEntity> items = new ArrayList<ColorimetryItemEntity>();
						for (PlanPlace p:plan.getPlanItems()) {
					 		ColorimetryItemEntity temp = new ColorimetryItemEntity();
							temp.setSampleId(p.getCode());
							temp.setSampleName(p.getPlaceName());
							items.add(temp);
						}
						((ColorimetryEntity)job).setItems(items);
						break;
					case "HYL":

						break;
					case "XHW":
						title="嗅和味检测任务["+code+"]";
						uri="/app/detection/smellandtaste-detail/{id}";
						job=new SmellandTasteEntity();
						job.setSampleDate(plan.getPlanDate());
						job.setDetector(t.getInspectorId()); 
						job.setDetectorName(t.getInspectorName()); 
						job.setPlanId(planId);
						job.setJobId(t.getId());
						
						List<SmellandTasteItemEntity> items_xhw = new ArrayList<SmellandTasteItemEntity>();
						for (PlanPlace p:plan.getPlanItems()) {
							SmellandTasteItemEntity temp = new SmellandTasteItemEntity();
							temp.setSampleId(p.getCode());
							temp.setSampleName(p.getPlaceName());
							items_xhw.add(temp);
						}
						((SmellandTasteEntity)job).setItems(items_xhw);
						break;
					case "HZD":
						title="浑浊度检测任务["+code+"]";
						uri="/app/detection/turbidity-detail/{id}";
						job=new TurbidityEntity();
						job.setSampleDate(plan.getPlanDate());
						job.setDetector(t.getInspectorId()); 
						job.setDetectorName(t.getInspectorName()); 
						job.setPlanId(planId);
						job.setJobId(t.getId());
						
						List<TurbidityItemEntity> items_hzd = new ArrayList<TurbidityItemEntity>();
						for (PlanPlace p:plan.getPlanItems()) {
							TurbidityItemEntity temp = new TurbidityItemEntity();
							temp.setSampleId(p.getCode());
							temp.setSampleName(p.getPlaceName());
							items_hzd.add(temp);
						}
						((TurbidityEntity)job).setItems(items_hzd);
						break;
					case "AD":

						break;
					case "PH":
						title="PH值检测任务["+code+"]";
						uri="/app/detection/phvalue-detail/{id}";
						job=new PHValueEntity();
						job.setSampleDate(plan.getPlanDate());
						job.setDetector(t.getInspectorId()); 
						job.setDetectorName(t.getInspectorName()); 
						job.setPlanId(planId);
						job.setJobId(t.getId());
						
						List<PHValueItemEntity> items_ph = new ArrayList<PHValueItemEntity>();
						for (PlanPlace p:plan.getPlanItems()) {
							PHValueItemEntity temp = new PHValueItemEntity();
							temp.setSampleId(p.getCode());
							temp.setSampleName(p.getPlaceName());
							items_ph.add(temp);
						}
						((PHValueEntity)job).setItems(items_ph);
						break;
					case "SW":

						break;
					case "XDJ":

						break;
					case "RYKJW":
						title="肉眼可见物检测任务["+code+"]";
						uri="/app/detection/nakedmatter-detail/{id}";
						job=new NakedMatterEntity();
						job.setSampleDate(plan.getPlanDate());
						job.setDetector(t.getInspectorId()); 
						job.setDetectorName(t.getInspectorName()); 
						job.setPlanId(planId);
						job.setJobId(t.getId());
						
						List<NakedMatterItemEntity> items_rykjw = new ArrayList<NakedMatterItemEntity>();
						for (PlanPlace p:plan.getPlanItems()) {
							NakedMatterItemEntity temp = new NakedMatterItemEntity();
							temp.setSampleId(p.getCode());
							temp.setSampleName(p.getPlaceName());
							items_rykjw.add(temp);
						}
						((NakedMatterEntity)job).setItems(items_rykjw);
						break;
					default:
						break;
				}
				if(job!=null)
					this.createFlow(job, "test", testFlow, uri, title, title);
			}
			plan.setStatus(3);
			plansrv.update(plan);
		}
		return "success";
	}
	
	
	@RequestMapping({"/createRep"})
	@ResponseBody
	public Object createRep(String planId) {
		PlanInfo plan = plansrv.get(planId);
		String msg="不能生成汇总：\n";
		boolean flag =true;
		for(PlanTestItem t:plan.getTestItems()){
			if(t.getStatus()==0){
				flag=false;
				msg+="【"+t.getTestName()+"】-"+t.getInspectorName()+"未完成！\n";
			}
		}
		if(flag){
			createRepData(plan);
			plan.setStatus(4);
			plansrv.update(plan);
			return MessageModel.createSuccessMessage(null, null);
		}
		else
			return MessageModel.createErrorMessage(msg,null);
	}
	
	private void createRepData(PlanInfo plan){
		
	}
	
	@RequestMapping({"/printTab"})
	public ModelAndView printTab(String id) {
		PlanInfo plan = plansrv.get(id);
		ModelAndView view = new ModelAndView("/app/plan/print-tab");
		view.addObject("list", plan.getPlanItems());
		return view;
	}
}


